<?php
namespace app\reservation\model;
use think\Loader;
use think\Validate;
use app\common\model\Base;
use app\common\model\Observice;
use app\common\model\ObserviceReceiveInterface;
/**
*会员预约课程
*预约课程的内容填写是由于教练决定的，所以这个类只负责生成向教练预约课程所需要的内容，以及条件判定
*同样的此类也不会继承任何类，不过类中使用Loader进行使用其他模块，会使用到Loader命名空间
*/
class ReservationCourse extends Base implements ObserviceReceiveInterface{
  protected $table = 'gym_reservation_course';
  protected static $inputData=[];
  protected static $member=null; //这个是需要多次使用的方法
  protected static $gymInfo = null;
  protected static  $autoPushCreateTime = true; //自动添加时间
  protected static $publicTool=null;
  /**
   * [initalizeReservationCourse 初始化课程预约的方法]
   * @return [type] [description]
   */
  protected static function initalizeReservationCourse(){
      //初始化会员签约模型
      $initializeModel = [
        'member'=>'\\app\\gym\\model\\MemberSigning',
        'gymInfo'=>'\\app\\gym\\model\\GymInfo',
      ];
      foreach($initializeModel as $key => $val){
          if(is_null(self::$$key)){
              self::$$key = Loader::model($val);
          }
      }
      self::$publicTool = Loader::controller('\\app\\publictool\\controller\\PublicTool');
      //初始化所有的类
  }
  /**
   * [由会员发起约课]
   * @return [type] [description]
   */
  public static function initiate(){
    $input = self::getInputData();
    $validate = new Validate(
      [
        'member_id'=>'require',
        'fitness_id'=>'require',
        'uniqid'=>'require'
      ],
      [
        'member_id.require'=>'会员的编号不能为空！',
        'fitness_id.require'=>'教练的编号不能为空！',
        'uniqid.require'=>'唯一标识不能为空！'
      ]
    );

    $validate->check($input)?:abort(-0026,$validate->getError());
    self::initalizeReservationCourse(); //初始化所有的类
    $gymInfo = self::$gymInfo;
    $member = self::$member;
    $publicTool = self::$publicTool;
    if(self::where(['reservation_person_id'=>$input['member_id'],'covenant_holder'=>$input['fitness_id']])->whereTime('create_time','today')->count()>0){
        abort(-0045,'您今天已经预约一次课程了，教练还没有忙完,再等等吧！');
    }
    $info = $gymInfo::info(['fitness_id'=>$input['fitness_id']]);
    //目前只判定单个健身房的情况
    $alreadySigning = $member::alreadySigning(1,$input['member_id'],$input['fitness_id'],implode(array_column($info,'gym_id')));
    if(!$alreadySigning){
        abort(-0001,'您并没有与该教练进行签约或已经解约！');
    }
    $input['gym_id'] = implode(array_column($info,'gym_id'));
    $restClassInfo = $member::restClassInfo($input);
    if(implode($restClassInfo) < 1){
        abort(-0002,'您的课时小于1,请联系教练购买课时！');
    }
    $data = $publicTool::replaceInputData([
      'reservation_person_id'=>'member_id', //约课人
      'covenant_holder'=>'fitness_id',//
    ],$input);
    $dataObject = new self();
    $dataObject->data($data)->allowField(['reservation_person_id','covenant_holder','create_time','gym_id','uniqid','message'])
    ->save();
    //通知教练有人预约课时！
    Observice::addObserivce('\\app\\user\\model\\AlertsMsg',
    ['addressee'=>$data['covenant_holder'], //收信人
    'addresser'=>$data['reservation_person_id'], //发信人
    'type'=>3, //类型
    'title'=>'约课申请', //内容
    'index_id'=>$dataObject->getLastInsID()]); //索引id
    //教练与学员进行约课需要通知教练一声
    Observice::notify(); //通知教练
  }
  /**
   * [receive 通知内容]
   * @return [type] [没有返回值]
   */
  public static function receive($message){
      self::setInputData($message);
      self::montify(); //修改内容
  }

  public static function montify(){
    $inputData = self::getInputData();
    $validate = new Validate(
      [
          'status'=>'require',
          'index_id'=>'require',
      ],
      [
        'status'=>'同意或者不同意必须存在！',
        'index_id'=>'索引值必须存在！'
      ]
    );
    if(!$validate->check($inputData)){
        abort(-0003,$validate->getError());
    }
    $allowField = ['status'];
    $dataObject = new self();
    $response = $dataObject->save(['status'=>self::$inputData('status')],['id'=>self::getInputData('index_id')]);
    if(!$response){
        abrot(-0004,'操作失败请重试！');
    }
    return true;
  }


  public static function info( $info = [] ){
      //通过唯一标识进行查询
      if(array_key_exists('uniqid',$info)){
           //查询正在审核中的
          $where = ['rc.uniqid'=>$info['uniqid'],'rc.status'=>2];
      }

      //通过主键的id进行查询
      if(array_key_exists('id',$info)){
          //查询正在审核中的
          $where = ['rc.id'=>$info['id'],'rc.status'=>2];
      }

      $field = [
          'rc.*',
          'usi.nick_name',
          'usi.name',
          'usi.head_figure',
      ];
      //查看约课申请是否存在
      if(self::where($where)->alias('rc')->count() > 0){

          $result = self::where($where)->alias('rc')->join('__USER_INFO__ usi','rc.reservation_person_id = usi.uuid','INNER')->field($field)->limit(1);

      }else{

          abort('没有找到会员的约课条目！');

      }


      //如果查询到了就进行返回
      return self::infoOfCache($result)[0];
  }


  /**
   * 生成唯一的id值
  */
  public static function genderQid(){
      $input = self::getInputData();
      $where = ['reservation_person_id'=>$input['uuid'],'status'=>2];
      $resultQuery = function($where){return self::where($where)->whereTime('create_time','today');};
      $uniqid = $resultQuery($where)->count() > 0 ? $resultQuery($where)->field(['uniqid'])->find()['uniqid'] : uniqid(substr($input['uuid'],-3).'_');
      return ['uniqid'=>$uniqid];
  }
}
